package cn.itsource.pethome.user.service.impl;

import cn.itsource.pethome.basic.util.MD5Utils;
import cn.itsource.pethome.basic.util.Result;
import cn.itsource.pethome.user.domain.LoginInfo;
import cn.itsource.pethome.user.domain.dto.UserDto;
import cn.itsource.pethome.user.mapper.LoginInfoMapper;
import cn.itsource.pethome.user.service.ILoginInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Service
public class LoginInfoServiceImpl implements ILoginInfoService {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    LoginInfoMapper loginInfoMapper;
    @Override
    public Result login(UserDto userDto) {
        //校验前端传来的数据并返回可登录的登录信息
        LoginInfo loginInfo = checkUserDto(userDto);
        //做类似于session的机制
        //1.随机产生一个值作为 token
        String token = UUID.randomUUID().toString();
        //2.类似于session  将登录对象存起来
        redisTemplate.opsForValue().set(token,loginInfo ,30 , TimeUnit.MINUTES);
        //将对应的仿session传到前端 （相当于把之前的jsessionID  和 登录对象传到前端）
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("loginUser", loginInfo);
        return new Result().setResultObj(map);

    }

    private LoginInfo checkUserDto(UserDto userDto) {
        //判断登录信息是否完整
        if (StringUtils.isEmpty(userDto.getUsername())||StringUtils.isEmpty(userDto.getPassword())
                ||StringUtils.isEmpty(userDto.getType())){
            throw new RuntimeException("请完善登录信息");
        }
        //根据传入的而用户名和用户类型（即后端管理员还是前端用户）查找对应的额登陆信息
        LoginInfo loginInfo = loginInfoMapper.loadByUserDto(userDto);
        //判断是否存在该用户
        if (loginInfo == null){
            throw new RuntimeException("该用户不存在");
        }
        //判断密码是否正确
        if (!loginInfo.getPassword().equals
                (MD5Utils.encrypByMd5(userDto.getPassword() + loginInfo.getSalt()))) {
            throw new RuntimeException("密码错误");
        }
        //判断用户是被禁用
        if (!loginInfo.getDisable()){
            throw new RuntimeException("该用户已被禁用，请联系管理员处理");
        }
        return loginInfo;
    }
}
